package work.hashmap;

import java.util.*;

public class Problem49 {
//    public List<List<String>> groupAnagrams(String[] strs) {
//        Map<String, List<String>> map = new HashMap<String, List<String>>();
//        for (String str : strs) {
//            char[] array = str.toCharArray();
//            Arrays.sort(array);
//            String key = new String(array);
//            List<String> list = map.getOrDefault(key, new ArrayList<String>());
//            list.add(str);
//            map.put(key, list);
//        }
//        return new ArrayList<List<String>>(map.values());
//        HashMap<String, List<String>> map = new HashMap<String,List<String>>();
//        for (String str : strs) {
//            char[] chars = str.toCharArray();
//            Arrays.sort(chars);
//            String newString =  chars.toString();
//            List<String> strings = map.getOrDefault(newString,new ArrayList<String>());
//            strings.add(str);
//            map.put(newString,strings);
//        }
//        return new ArrayList<List<String>>(map.values());
//}


    public static void main(String[] args) {
        Problem49 test = new Problem49();
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        test.groupAnagrams(strs);

    }

    //11复习
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String newString = String.valueOf(chars);
            List<String> list = map.getOrDefault(newString, new ArrayList<>());
            list.add(str);
            map.put(newString, list);
            ArrayList<String> objects = new ArrayList<>();
            objects.add("dd");
            objects.add("ss");
        }
        //这里为什么是Arryalist而不是List<List<String>>呢，因为List是接口不能进行实例化
        return new ArrayList<>(map.values());
    }

    public List<List<String>> groupAnagrams2(String[] strs) {
        HashMap<String, List<String>> map = new HashMap<>();
        for (String str : strs) {
            char[] charArray = str.toCharArray();
            Arrays.sort(charArray);
            String string = new String(charArray);
            List<String> orDefault = map.getOrDefault(string, new ArrayList<>());
            orDefault.add(str);
            map.put(string, orDefault);
        }
//        return new ArrayList<List<String>>(map.values());


        ArrayList<List<String>> objects = new ArrayList<>();
        for (String key : map.keySet()) {
            objects.add(map.get(key));
        }
        return objects;
    }

}
